package com.gict.antifraudback.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gict.antifraudback.entity.Menu;
import com.gict.antifraudback.service.MenuService;
import com.gict.antifraudback.mapper.MenuMapper;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
* @author XIE
* @description 针对表【menu】的数据库操作Service实现
* @createDate 2023-11-02 15:18:53
*/
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu>
    implements MenuService{


    /**
     * 转成树
     *
     * @param menuList
     * @return
     */
    @Override
    public List<Menu> buildTree(List<Menu> menuList) {
        List<Menu> tree = new ArrayList<>();
        for (Menu menu : menuList) {
            if (menu.getParentId() == 0) {
                // 根节点
                tree.add(menu);
            } else {
                // 非根节点，将其加入父节点的 children 列表
                findParentAndAddChild(tree, menu);
            }
        }
        return tree;
    }

    private void findParentAndAddChild(List<Menu> tree, Menu child) {
        for (Menu parent : tree) {
            if (parent.getChildren() == null) {
                parent.setChildren(new ArrayList<>());
            }
            if (Objects.equals(child.getParentId(), parent.getId())) {
                parent.getChildren().add(child);
            } else {
                // 递归查找父节点
                findParentAndAddChild(parent.getChildren(), child);
            }
        }
    }

}




